package com.example.forumsystem.exception;

import com.example.forumsystem.common.AppResult;
import com.example.forumsystem.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 全局异常处理
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(ApplicationException.class) // 指定处理的异常和范围
    public AppResult applicationException(ApplicationException e) {
        // 打印日志
      log.error(e.getMessage());
      // 返回持有的错误信息
      if(e.getErrorResult() != null) {
          return e.getErrorResult();
      }
      // 非空校验
      if(e.getMessage() == null || e.getMessage() == "") {
          return AppResult.failed(ResultCode.ERROR_SERVICES);
      }
      // 返回具体异常信息
      return AppResult.failed(e.getMessage());
    }
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public AppResult exceptionHandler(Exception e) {
        // 打印日志
        e.printStackTrace();
        log.error(e.getMessage());
        // 非空校验
        if(e.getMessage() != null || e.getMessage() != "") {
            return AppResult.failed(e.getMessage());
        }
        // 返回异常信息
        return AppResult.failed(ResultCode.ERROR_SERVICES);
    }
}
